import { kernel } from '@/ts/base';
import { IProductBase, ProductBase } from './productBase';
import { IWorkTask } from '../../work/task';

export class ProductManager {
  constructor(task: IWorkTask) {
    this.task = task;
  }

  private task: IWorkTask;
  private productList: IProductBase[] = [];
  private collName: string = 'goods-sync';

  /**
   * 添加商品到批次
   */
  addProduct(product: IProductBase): void {
    this.productList.push(product);
  }

  /**
   * 批量添加商品
   */
  addProductList(productList: IProductBase[]): void {
    productList.forEach((productData) => {
      this.productList.push(new ProductBase(productData));
    });
  }

  /**
   * 批量保存商品信息
   */
  async saveBatch(): Promise<boolean> {
    try {
      const {
        task: {
          taskdata: { belongId },
        },
        productList,
        collName,
      } = this;
      const result = await kernel.collectionReplace(
        belongId,
        belongId,
        [belongId],
        collName,
        productList,
      );
      return result.success;
    } catch (error) {
      console.error('批量保存商品失败:', error);
      return false;
    }
  }

  /**
   * 获取当前批次中的所有商品
   */
  getProductList(): IProductBase[] {
    return this.productList;
  }

  /**
   * 清空当前批次
   */
  clear(): void {
    this.productList = [];
  }
}
